package com.tql.test_02;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class JUCPCTest1 {

    public static void main(String[] args) {
        Task1 task1=new Task1();
        new Thread(()->{ for (int i = 0; i < 10; i++) task1.printA(); },"A").start();
        new Thread(()->{ for (int i = 0; i < 10; i++) task1.printB(); },"B").start();
        new Thread(()->{ for (int i = 0; i < 10; i++)task1.printC(); },"C").start();
    }
}
//线程要处理的资源类，实现解耦操作
class Task1{
    //标志位
    private int num=1; //1A 2B 3C
    private Lock lock=new ReentrantLock();
    //Condition 取代对象监视器 ，有点可以是实现精准唤醒线程
    private Condition conditionA=lock.newCondition();
    //Condition 取代对象监视器 ，有点可以是实现精准唤醒线程
    private Condition conditionB=lock.newCondition();
    //Condition 取代对象监视器 ，有点可以是实现精准唤醒线程
    private Condition conditionC=lock.newCondition();
    public void printA(){
        lock.lock();
        try {
            while(num!=1){
                try {
                    conditionA.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName()+">>>>AAAAAAA");
            num=2;
            conditionB.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
            lock.unlock();
    }
    public void printB(){
        lock.lock();
        try {
            while(num!=2){
                try {
                    conditionB.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName()+">>>>BBBBBBBBBBB");
            num=3;
            conditionC.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public void printC(){
        lock.lock();
        try {
            while(num!=3){
                try {
                    conditionC.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName()+">>>>CCCCCCCCCC");
            num=1;
            conditionA.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}